﻿using System;
using System.Collections.Generic;

namespace InfiniTec.Collections.Generic
{
	public class KeyedCollection<TKey, T> : System.Collections.ObjectModel.KeyedCollection<TKey, T>
	{
		private Func<T, TKey> _KeySelector;

		public void AddRange(IEnumerable<T> items)
		{
			if (items == null) throw new ArgumentNullException("items");
			items.Foreach(Add);
		}

		public KeyedCollection(Func<T, TKey> keySelector)
		{
			Initialize(keySelector);
		}

		private void Initialize(Func<T, TKey> keySelector)
		{
			if (keySelector == null) throw new ArgumentNullException("keySelector");
			_KeySelector = keySelector;
		}

		public KeyedCollection(Func<T, TKey> keySelector, IEqualityComparer<TKey> comparer) : base(comparer)
		{
			Initialize(keySelector);
		}

		public bool TryGetItem(TKey key, out T item)
		{
			return Dictionary.TryGetValue(key, out item);
		}

		protected override TKey GetKeyForItem(T item)
		{
			return _KeySelector(item);
		}
	}
}
